
package biblio.service.category;


import biblio.domain.Category;
import java.util.List;
import java.util.ArrayList;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import org.apache.log4j.Logger;


/**
 * Validates setting parent id of category.
 * @author mephisto
 */
@ManagedBean
@RequestScoped
public class ParentCategoryValidator implements Validator
{

    public void validate(FacesContext context, UIComponent component, Object value)
            throws ValidatorException
    {
        int editedCatId = categoryList.getEditedCategory().getId();
        List<Integer> parentIdList = 
                new ArrayList<Integer>(autocompleteCategory.getCategories().size()-1);
        for (Category it : autocompleteCategory.getCategories())
            if (it.getId() > 0 && it.getId() != editedCatId)
                parentIdList.add(it.getId());
        
        if (value !=  null)
        {
            Integer val = null;
            log.info("Value to validate: " + val);
            try
            {
                val = Integer.parseInt(value.toString().trim());
            }
            catch (NumberFormatException e)
            {
                log.warn(val + " is not a number!");
                FacesMessage message = new FacesMessage(
                           "Error by setting parent id of category",
                            val + " is not a number!");
                message.setSeverity(FacesMessage.SEVERITY_ERROR);
                throw new ValidatorException(message);
            }
            if (parentIdList.indexOf(val) == -1)
            {
                log.warn("Validation failure!: " + val);
                FacesMessage message = new FacesMessage(
                           "Error by setting parent id of category", 
                           "Category with chosen " + val + " id does not exist!");
                message.setSeverity(FacesMessage.SEVERITY_ERROR);
                throw new ValidatorException(message);
            }
            else
                log.debug("Value is ok: " + val);
        }
    }

    public void setAutocompleteCategory(AutocompleteCategory autocompleteCategory)
    {
        this.autocompleteCategory = autocompleteCategory;
    }

    public void setCategoryList(CategoryList categoryList)
    {
        this.categoryList = categoryList;
    }

    
    private static Logger log = Logger.getLogger(ParentCategoryValidator.class);
    @ManagedProperty(value="#{autocompleteCategory}")
    private AutocompleteCategory autocompleteCategory;
    @ManagedProperty(value="#{catList}")
    private CategoryList categoryList;
}
